

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';

interface Message {
  id: string;
  title: string;
  content: string;
  type: 'announcement' | 'enrollment' | 'learning';
  sendTime: string;
  isRead: boolean;
  detailContent: string;
}

type FilterType = 'all' | 'announcement' | 'enrollment' | 'learning' | 'unread';
type SortType = 'time-desc' | 'time-asc' | 'status';

const MessagesPage: React.FC = () => {
  const navigate = useNavigate();
  
  const [currentFilter, setCurrentFilter] = useState<FilterType>('all');
  const [currentSort, setCurrentSort] = useState<SortType>('time-desc');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);


  const [messages, setMessages] = useState<Message[]>([
    {
      id: 'msg_001',
      title: '2024年春季学期课程报名开始',
      content: '新的学期即将开始，欢迎各位同学报名参加我们的优质课程...',
      type: 'announcement',
      sendTime: '2024-01-15 10:30',
      isRead: false,
      detailContent: `
        <p>亲爱的同学：</p>
        <br>
        <p>新的学期即将开始，我们很高兴地宣布2024年春季学期课程报名正式启动！</p>
        <br>
        <p>本次春季学期我们为大家准备了丰富多样的优质课程，涵盖计算机、管理、语言等多个领域。所有课程均由经验丰富的教师授课，采用线上线下相结合的教学模式，确保学习效果。</p>
        <br>
        <p><strong>重要时间节点：</strong></p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>报名开始时间：2024年1月15日</li>
          <li>报名截止时间：2024年1月31日</li>
          <li>课程开始时间：2024年2月1日</li>
        </ul>
        <br>
        <p>请同学们及时登录系统查看课程详情并完成报名。如有任何问题，欢迎随时联系我们的客服团队。</p>
        <br>
        <p>祝大家学习愉快！</p>
        <br>
        <p>学途教育团队</p>
      `
    },
    {
      id: 'msg_002',
      title: 'Python编程基础课程报名成功',
      content: '恭喜您成功报名Python编程基础课程，课程将在2024年2月1日开始...',
      type: 'enrollment',
      sendTime: '2024-01-14 15:20',
      isRead: false,
      detailContent: `
        <p>亲爱的张同学：</p>
        <br>
        <p>恭喜您成功报名Python编程基础课程！</p>
        <br>
        <p>课程信息：</p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>课程名称：Python编程基础</li>
          <li>讲师：李教授</li>
          <li>开始时间：2024年2月1日 19:00</li>
          <li>课程时长：8周，每周2次课</li>
        </ul>
        <br>
        <p>我们已将课程大纲和相关学习资料发送至您的邮箱，请及时查收。课程将采用线上直播+录播的形式进行，您可以在"我的课程"中查看详细安排。</p>
        <br>
        <p>如有任何疑问，请随时联系课程助教或客服团队。</p>
        <br>
        <p>祝您学习顺利！</p>
        <br>
        <p>学途教育团队</p>
      `
    },
    {
      id: 'msg_003',
      title: '数据分析课程即将开始',
      content: '您报名的数据分析与可视化课程将在明天开始，请做好学习准备...',
      type: 'learning',
      sendTime: '2024-01-14 09:15',
      isRead: false,
      detailContent: `
        <p>亲爱的张同学：</p>
        <br>
        <p>温馨提醒：您报名的数据分析与可视化课程即将开始！</p>
        <br>
        <p>课程信息：</p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>课程名称：数据分析与可视化</li>
          <li>开始时间：2024年1月15日 14:00</li>
          <li>上课方式：线上直播</li>
          <li>课程平台：学途在线课堂</li>
        </ul>
        <br>
        <p>请您提前做好以下准备：</p>
        <ol class="list-decimal list-inside ml-4 space-y-1">
          <li>确保网络连接稳定</li>
          <li>准备好笔记本和笔</li>
          <li>提前10分钟进入课堂</li>
          <li>如有技术问题请及时联系助教</li>
        </ol>
        <br>
        <p>期待在课堂上与您相见！</p>
        <br>
        <p>学途教育团队</p>
      `
    },
    {
      id: 'msg_004',
      title: '系统维护通知',
      content: '为了提供更好的服务体验，我们将于本周日进行系统维护...',
      type: 'announcement',
      sendTime: '2024-01-12 16:45',
      isRead: true,
      detailContent: `
        <p>亲爱的用户：</p>
        <br>
        <p>为了提供更好的服务体验，我们将于本周日进行系统维护。</p>
        <br>
        <p><strong>维护时间：</strong>2024年1月14日 02:00 - 06:00（预计4小时）</p>
        <br>
        <p><strong>维护期间影响：</strong></p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>用户登录功能可能受到影响</li>
          <li>课程观看功能可能暂时不可用</li>
          <li>报名和支付功能暂停</li>
        </ul>
        <br>
        <p>我们会尽量缩短维护时间，给您带来的不便敬请谅解。如有紧急问题，请联系客服热线：400-123-4567。</p>
        <br>
        <p>感谢您的理解与支持！</p>
        <br>
        <p>学途技术团队</p>
      `
    },
    {
      id: 'msg_005',
      title: '项目管理实战课程报名成功',
      content: '恭喜您成功报名项目管理实战课程，课程资料已发送至您的邮箱...',
      type: 'enrollment',
      sendTime: '2024-01-10 11:30',
      isRead: true,
      detailContent: `
        <p>亲爱的张同学：</p>
        <br>
        <p>恭喜您成功报名项目管理实战课程！</p>
        <br>
        <p>课程信息：</p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>课程名称：项目管理实战</li>
          <li>讲师：张经理</li>
          <li>开始时间：2024年2月5日 19:30</li>
          <li>课程形式：线上直播+案例分析</li>
        </ul>
        <br>
        <p>课程资料已发送至您的邮箱，包括：</p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>课程大纲</li>
          <li>预习资料</li>
          <li>项目管理工具介绍</li>
          <li>往期优秀案例</li>
        </ul>
        <br>
        <p>请您在开课前完成预习，以便更好地参与课堂讨论。如有任何问题，欢迎在课程讨论区留言或联系助教。</p>
        <br>
        <p>祝您学习愉快！</p>
        <br>
        <p>学途教育团队</p>
      `
    },
    {
      id: 'msg_006',
      title: 'Python课程第一周作业提醒',
      content: 'Python编程基础课程第一周作业已发布，请在截止日期前完成...',
      type: 'learning',
      sendTime: '2024-01-08 14:20',
      isRead: true,
      detailContent: `
        <p>亲爱的张同学：</p>
        <br>
        <p>Python编程基础课程第一周作业已发布，请及时完成。</p>
        <br>
        <p><strong>作业信息：</strong></p>
        <ul class="list-disc list-inside ml-4 space-y-1">
          <li>作业主题：Python基础语法练习</li>
          <li>截止时间：2024年1月18日 23:59</li>
          <li>提交方式：在线提交</li>
          <li>作业链接：<a href="#" class="text-primary hover:underline">点击提交</a></li>
        </ul>
        <br>
        <p>本次作业主要考察：</p>
        <ol class="list-decimal list-inside ml-4 space-y-1">
          <li>变量和数据类型</li>
          <li>条件语句</li>
          <li>循环结构</li>
          <li>简单函数定义</li>
        </ol>
        <br>
        <p>完成作业后，您可以获得相应的学分。如有疑问，请在课程讨论区提问或联系助教。</p>
        <br>
        <p>加油！</p>
        <br>
        <p>Python课程助教团队</p>
      `
    }
  ]);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '站内信 - 学途';
    return () => { document.title = originalTitle; };
  }, []);

  // 计算未读消息数量
  const unreadCount = messages.filter(msg => !msg.isRead).length;

  // 筛选消息
  const filteredMessages = messages.filter(message => {
    if (currentFilter === 'announcement' && message.type !== 'announcement') return false;
    if (currentFilter === 'enrollment' && message.type !== 'enrollment') return false;
    if (currentFilter === 'learning' && message.type !== 'learning') return false;
    if (currentFilter === 'unread' && message.isRead) return false;
    
    return true;
  });

  // 排序消息
  const sortedMessages = [...filteredMessages].sort((a, b) => {
    switch (currentSort) {
      case 'time-asc':
        return new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime();
      case 'time-desc':
        return new Date(b.sendTime).getTime() - new Date(a.sendTime).getTime();
      case 'status':
        if (!a.isRead && b.isRead) return -1;
        if (a.isRead && !b.isRead) return 1;
        return 0;
      default:
        return 0;
    }
  });

  // 处理筛选切换
  const handleFilterChange = (filterType: FilterType) => {
    setCurrentFilter(filterType);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理排序切换
  const handleSortChange = (sortType: SortType) => {
    setCurrentSort(sortType);
  };

  // 标记消息为已读
  const handleMarkAsRead = (messageId: string) => {
    setMessages(prevMessages => 
      prevMessages.map(msg => 
        msg.id === messageId ? { ...msg, isRead: true } : msg
      )
    );
  };

  // 标记消息为未读
  const handleMarkAsUnread = (messageId: string) => {
    setMessages(prevMessages => 
      prevMessages.map(msg => 
        msg.id === messageId ? { ...msg, isRead: false } : msg
      )
    );
  };

  // 全部已读
  const handleMarkAllAsRead = () => {
    setMessages(prevMessages => 
      prevMessages.map(msg => ({ ...msg, isRead: true }))
    );
  };

  // 查看消息详情
  const handleMessageClick = (message: Message) => {
    setSelectedMessage(message);
    setIsModalVisible(true);
    
    // 如果消息未读，自动标记为已读
    if (!message.isRead) {
      handleMarkAsRead(message.id);
    }
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setIsModalVisible(false);
    setSelectedMessage(null);
  };



  // 处理分页
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 处理每页条数变更
  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setCurrentPage(1); // 重置到第一页
  };

  // 获取消息类型显示文本和样式
  const getMessageTypeInfo = (type: Message['type']) => {
    switch (type) {
      case 'announcement':
        return { text: '系统公告', className: 'bg-info bg-opacity-10 text-info' };
      case 'enrollment':
        return { text: '报名通知', className: 'bg-success bg-opacity-10 text-success' };
      case 'learning':
        return { text: '学习提醒', className: 'bg-warning bg-opacity-10 text-warning' };
      default:
        return { text: '系统公告', className: 'bg-info bg-opacity-10 text-info' };
    }
  };

  return (
    <Layout title="站内信 - 学途">
      <div className="flex min-h-screen bg-gray-50">
        {/* 左侧菜单 */}
        <aside className="w-64 bg-white border-r border-gray-200 min-h-screen">
          <nav className="p-4">
            {/* 个人中心菜单 */}
            <div>
              <Link to="/personal-center" className="flex items-center space-x-3 px-4 py-3 mb-4 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg transition-colors">
                <i className="fas fa-user text-lg"></i>
                <span className="font-medium">个人中心</span>
              </Link>
              <ul className="space-y-1">
                <li>
                  <Link to="/personal-info" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-user-edit text-base"></i>
                    <span>个人信息</span>
                  </Link>
                </li>
                <li>
                  <Link to="/enrolled-courses" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-book-open text-base"></i>
                    <span>已报名课程</span>
                  </Link>
                </li>
                <li>
                  <Link to="/messages" className="flex items-center space-x-3 px-4 py-2 bg-blue-50 text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-envelope text-base"></i>
                    <span>站内信</span>
                  </Link>
                </li>
                <li>
                  <Link to="/account-security" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-shield-alt text-base"></i>
                    <span>账户安全</span>
                  </Link>
                </li>
              </ul>
            </div>
          </nav>
        </aside>

        {/* 主内容区域 */}
        <main className="flex-1 min-w-0">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            {/* 页面头部 */}
            <div className="mb-8">
              {/* 面包屑导航 */}
              <nav className="mb-4">
                <ol className="flex items-center space-x-2 text-sm text-gray-600">
                  <li>
                    <Link to="/home" className="hover:text-blue-600 transition-colors">首页</Link>
                  </li>
                  <li>
                    <i className="fas fa-chevron-right text-xs"></i>
                  </li>
                  <li>
                    <Link to="/personal-center" className="hover:text-blue-600 transition-colors">个人中心</Link>
                  </li>
                  <li>
                    <i className="fas fa-chevron-right text-xs"></i>
                  </li>
                  <li className="text-gray-900">站内信</li>
                </ol>
              </nav>
              
              <div className="flex items-center justify-between">
                <h1 className="text-3xl font-bold text-gray-900">站内信</h1>
                <div className="flex items-center space-x-3">
                  {unreadCount > 0 && (
                    <span className="px-3 py-1 bg-red-600 text-white text-sm rounded-full">{unreadCount}</span>
                  )}
                  <button 
                    onClick={handleMarkAllAsRead}
                    className="px-4 py-2 text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-600 hover:text-white transition-colors"
                  >
                    全部已读
                  </button>
                </div>
              </div>
            </div>

            {/* 工具栏区域 */}
            <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
                {/* 筛选标签 */}
                <div className="flex flex-wrap gap-2">
                  <button 
                    onClick={() => handleFilterChange('all')}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                      currentFilter === 'all' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    全部消息 ({messages.length})
                  </button>
                  <button 
                    onClick={() => handleFilterChange('announcement')}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                      currentFilter === 'announcement' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    系统公告 ({messages.filter(m => m.type === 'announcement').length})
                  </button>
                  <button 
                    onClick={() => handleFilterChange('enrollment')}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                      currentFilter === 'enrollment' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    报名通知 ({messages.filter(m => m.type === 'enrollment').length})
                  </button>
                  <button 
                    onClick={() => handleFilterChange('learning')}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                      currentFilter === 'learning' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    学习提醒 ({messages.filter(m => m.type === 'learning').length})
                  </button>
                  <button 
                    onClick={() => handleFilterChange('unread')}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                      currentFilter === 'unread' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    未读消息 ({unreadCount})
                  </button>
                </div>
                
                {/* 排序选择 */}
                <div className="flex items-center space-x-4">
                  <span className="text-gray-600 text-sm">排序：</span>
                  <select 
                    value={currentSort}
                    onChange={(e) => handleSortChange(e.target.value as SortType)}
                    className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="time-desc">时间倒序</option>
                    <option value="time-asc">时间正序</option>
                    <option value="status">状态排序</option>
                  </select>
                </div>
              </div>
            </div>

            {/* 站内信列表 */}
            <div className="bg-white rounded-xl shadow-lg overflow-hidden">
              {/* 消息列表头部 */}
              <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
                <div className="grid grid-cols-12 gap-4 text-sm font-medium text-gray-600">
                  <div className="col-span-6">标题</div>
                  <div className="col-span-2">类型</div>
                  <div className="col-span-2">发送时间</div>
                  <div className="col-span-1">状态</div>
                  <div className="col-span-1">操作</div>
                </div>
              </div>
              
              {/* 消息列表内容 */}
              <div className="divide-y divide-gray-100">
                {sortedMessages.map((message) => {
                  const typeInfo = getMessageTypeInfo(message.type);
                  return (
                    <div 
                      key={message.id}
                      onClick={() => handleMessageClick(message)}
                      className={`px-6 py-4 cursor-pointer hover:bg-gray-50 transition-colors ${!message.isRead ? 'bg-blue-50' : ''}`}
                    >
                      <div className="grid grid-cols-12 gap-4 items-center">
                        <div className="col-span-6">
                          <h3 className="font-medium text-gray-900">{message.title}</h3>
                          <p className="text-gray-600 text-sm mt-1">{message.content}</p>
                        </div>
                        <div className="col-span-2">
                          <span className={`px-2 py-1 ${typeInfo.className} text-xs rounded-full`}>
                            {typeInfo.text}
                          </span>
                        </div>
                        <div className="col-span-2 text-gray-600 text-sm">{message.sendTime}</div>
                        <div className="col-span-1">
                          {!message.isRead ? (
                            <>
                              <span className="w-2 h-2 bg-blue-600 rounded-full inline-block"></span>
                              <span className="text-blue-600 text-sm ml-1">未读</span>
                            </>
                          ) : (
                            <span className="text-gray-600 text-sm">已读</span>
                          )}
                        </div>
                        <div className="col-span-1">
                          <button 
                            onClick={(e) => {
                              e.stopPropagation();
                              if (!message.isRead) {
                                handleMarkAsRead(message.id);
                              } else {
                                handleMarkAsUnread(message.id);
                              }
                            }}
                            className="text-gray-600 hover:text-blue-600 transition-colors"
                          >
                            <i className={`fas ${message.isRead ? 'fa-circle' : 'fa-check-circle'}`}></i>
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 分页区域 */}
            <div className="flex items-center justify-between mt-6">
              <div className="flex items-center space-x-4 text-gray-600 text-sm">
                <span>共 <span className="font-medium text-gray-900">{sortedMessages.length}</span> 条消息</span>
                <select 
                  value={pageSize}
                  onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                  className="px-2 py-1 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="10">每页 10 条</option>
                  <option value="20">每页 20 条</option>
                  <option value="50">每页 50 条</option>
                </select>
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-50 transition-colors disabled:opacity-50"
                >
                  <i className="fas fa-chevron-left"></i>
                </button>
                {[1, 2, 3].map((page) => (
                  <button 
                    key={page}
                    onClick={() => handlePageChange(page)}
                    className={`px-3 py-1 rounded transition-colors ${
                      currentPage === page 
                        ? 'bg-blue-600 text-white' 
                        : 'border border-gray-300 hover:bg-gray-50'
                    }`}
                  >
                    {page}
                  </button>
                ))}
                <span className="px-2 text-gray-600">...</span>
                <button 
                  onClick={() => handlePageChange(10)}
                  className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-50 transition-colors"
                >
                  10
                </button>
                <button 
                  onClick={() => handlePageChange(currentPage + 1)}
                  className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-50 transition-colors"
                >
                  <i className="fas fa-chevron-right"></i>
                </button>
              </div>
            </div>
          </div>
        </main>
      </div>

      {/* 消息详情模态弹窗 */}
      {isModalVisible && selectedMessage && (
        <div className="fixed inset-0 z-50">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={handleCloseModal}></div>
          <div className="relative flex items-center justify-center min-h-screen p-4">
            <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden">
              {/* 弹窗头部 */}
              <div className="flex items-center justify-between p-6 border-b border-gray-200">
                <h2 className="text-xl font-semibold text-gray-900">消息详情</h2>
                <button 
                  onClick={handleCloseModal}
                  className="text-gray-600 hover:text-gray-900 transition-colors"
                >
                  <i className="fas fa-times text-xl"></i>
                </button>
              </div>
              
              {/* 弹窗内容 */}
              <div className="p-6 overflow-y-auto max-h-[60vh]">
                <div className="space-y-4">
                  <div className="flex items-center space-x-4">
                    <span className={`px-3 py-1 ${getMessageTypeInfo(selectedMessage.type).className} text-sm rounded-full`}>
                      {getMessageTypeInfo(selectedMessage.type).text}
                    </span>
                    <span className="text-text-secondary text-sm">{selectedMessage.sendTime}</span>
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900">{selectedMessage.title}</h3>
                  <div 
                    className="text-gray-600 leading-relaxed"
                    dangerouslySetInnerHTML={{ __html: selectedMessage.detailContent }}
                  />
                </div>
              </div>
              
              {/* 弹窗底部 */}
              <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200 bg-gray-50">
                <button 
                  onClick={handleCloseModal}
                  className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Layout>
  );
};

export default MessagesPage;

